package com.hurl.waguji.biz.download;

import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.testng.log4testng.Logger;

import com.hurl.library.spider.SpiderException;
import com.hurl.library.spider.UrlPattern;
import com.hurl.library.util.DateUtils;
import com.hurl.library.util.StringUtils;
import com.hurl.waguji.base.DateService;
import com.hurl.waguji.base.Formatter;
import com.hurl.waguji.base.SqlReader;
import com.hurl.waguji.base.dataprocess.ProcessParams;
import com.hurl.waguji.persistence.DmGpBO;
import com.hurl.waguji.persistence.JcsjCjmxFbmxHexunBO;

class MrhqCjmxFbmxHexunProcessor extends BaseDownloadProcessor {
	public MrhqCjmxFbmxHexunProcessor(ProcessParams params,
			DownloadIdentifier identifier) {
		super(params, identifier);
		context.setBoSaveMode(DownloadContext.BO_SAVE_MODE_INSERT);
	}

	private static final Logger log = Logger.getLogger(MrhqCjmxFbmxHexunProcessor.class);

	private Date lastTradingTime;
	private Date lastTradingDate;


	@Override
	public void downloadFailure(String url, Throwable e) throws SpiderException {
		throw new SpiderException("下载出错",e);
	}

	@Override
	public Date getRq() {
		return lastTradingDate;
	}

	@Override
	public void validate() throws Throwable {
		lastTradingTime = DateService.getLastTradingTimeFromWeb();
		lastTradingDate = DateUtils.getDate(this.lastTradingTime);
		
		/*if(!DateService.isNowAfterTradingTime(lastTradingTime)){
			throw new SpiderException("只能在交易日当天下午下载！");
		}*/

		log.info("检查数据是否已经下载过。");
		if(isAlreadyDownloaded()){
			throw new SpiderException(DateUtils.formatDate(getRq(), DateUtils.FORMAT_DATE_CN)+"的数据已经下载过！");
		}
		log.info("没有下载过，开始下载。。。");
		/* 先清除上一次已经下载了的不完整的数据 */
//		context.getDao().queryByHQL("delete from "+JcsjCjmxFbmxHexunBO.class.getSimpleName()+" where id.rq=:rq").setDate("rq", lastTradingDate).executeUpdate();
	
	}

	@Override
	public boolean beforeDownload(String url) throws SpiderException {
		/* 下载过的项就不要重复下载了 */
		if(context.getDao().queryBySQL(SqlReader.getSql("SQL12041402",new String[]{context.getEnvAsString("gpdm"),DateUtils.formatDate(getRq(), "yyyy-MM-dd")})).list().size()>0){
			return false;
		}
		return true;
	}

	@Override
	public void convertHTML2BO(String url, String html, BOSaver collector) {
		
		//没有该股票信息，退出
		if(StringUtils.isEmpty(html) || html.contains("nostock")){
			return ;
		}
		
		String gpdm = StringUtils.substringBetween(url, "gpdm=", null);
		
		try {
			JSONArray jsonarray = null;
			jsonarray = new JSONArray(html);
			
			//数据量不对，退出
			if(jsonarray==null || jsonarray.length()<2){
				return ;
			}
			//取出第一行，获取股票名称和数据生成时间。
			JSONArray obj1 = (JSONArray)jsonarray.get(0);
			Date gxrq = Formatter.toDate(obj1.getString(2),"yyyy年MM月dd日 HH:mm");
			lastTradingDate = DateUtils.getDate(gxrq);
			
			JcsjCjmxFbmxHexunBO bo = null;
			for(int i=1; i<jsonarray.length();i++){
				JSONArray item = (JSONArray)jsonarray.get(i);
				bo = new JcsjCjmxFbmxHexunBO();
				bo.setGpdm(gpdm);
				bo.setRq(lastTradingDate);
				bo.setSj(Formatter.toDate(item.getString(0),"HH:mm:ss"));
				bo.setCjl(item.getInt(1));
				bo.setCjjg(item.getDouble(2));
				bo.setCjje(item.getDouble(3));
				bo.setMmp(item.getString(5));
				bo.setLastupdate(gxrq);
				collector.addBO(bo);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			context.setStopWithError(e);
		}
	}

	@Override
	public void shutdown(boolean success, Throwable t) {
		if(!success){
//			context.getDao().queryByHQL("delete from "+JcsjCjmxFbmxHexunBO.class.getSimpleName()+" where id.rq=:rq").setDate("rq", lastTradingDate).executeUpdate();
		}
	}

	@Override
	public UrlPattern getUrlPattern() {
		return new StockIteratorUrlPattern(context) {
			@Override
			public String bo2url(DmGpBO bo) {
				return "http://vol.stock.hexun.com/Now/Share/DealDetail_1.ashx?code="+bo.getGpDmJ()+"&gpdm="+bo.getGpDm();
			}
		};
	}
}
